package org.bopis.services.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bopis.general.Constantes;

/**
 * Clase que se encarga del envio de correos electrónicos
 * @author i.fernandezmolina
 *
 */
public class MailSender {
		
	private Log log = LogFactory.getLog(MailSender.class);

	public void sendEmail(String emailDestinatario, String nombreDestinatario, String asunto, String mensaje) throws Exception{
		
		Properties props = new Properties();
		props.put("mail.smtp.host", Constantes.MAIL_SMTP_HOST);
		props.put("mail.smtp.socketFactory.port", Constantes.MAIL_SMTP_SOCKETFACTORY_PORT);
		props.put("mail.smtp.socketFactory.class", Constantes.MAIL_SMTP_SOCKETFACTORY_CLASS);
		props.put("mail.smtp.auth", Constantes.MAIL_SMTP_AUTH);
		props.put("mail.smtp.port", Constantes.MAIL_SMTP_PORT);
 
		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(Constantes.MAIL_USER, Constantes.MAIL_PASSWORD);
				}
			});
 
		try {
 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(Constantes.MAIL_ACCOUNT));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailDestinatario));
			message.setSubject(asunto);
			message.setText(mensaje);
 
			Transport.send(message);
 
			log.info("Email enviado");
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
		
	}
	
}
